package examples3;

import co.paralleluniverse.fibers.Suspendable;
import net.corda.core.contracts.StateAndRef;
import net.corda.core.flows.*;
import net.corda.core.identity.CordaX500Name;
import net.corda.core.identity.Party;
import net.corda.core.node.NodeInfo;
import net.corda.core.node.ServiceHub;

import java.util.List;


/***
 * rpc 发送方
 */
@InitiatingFlow
@StartableByRPC
public class TwoPartyInitiatingFlow extends FlowLogic<Integer> {

    private Party counterParty;

    private int number;

    public TwoPartyInitiatingFlow(Party counterParty, int number) {
        this.counterParty = counterParty;
        this.number = number;
    }

    @Suspendable
    public Integer call() throws FlowException {

        //最简单的发送例子
//        int number = 5;
//        FlowSession session = initiateFlow(counterParty);
//        session.send(number);
//        int receivedPlusOneInt = session.receive(Integer.class).unwrap(it->it);
//        return receivedPlusOneInt;

        // Service Hub 只有在flow流程处理的时候才能接触到Service Hub
        ServiceHub serviceHub = getServiceHub();

        //获取以前所有的houseState的历史记录
        List<StateAndRef<HouseState>> stateFromVault
                = serviceHub.getVaultService().queryBy(HouseState.class).getStates();

        //获取与Alice、Shanghai、CN 有关的HouseState
        CordaX500Name aliceName = new CordaX500Name("Alice","Shanghai","CN");

        NodeInfo aliceNode = serviceHub.getNetworkMapCache().getNodeByLegalName(aliceName);

        //获取第一条信息
        Party alice = aliceNode.getLegalIdentities().get(0);

        int platfromVersion = serviceHub.getMyInfo().getPlatformVersion();

        FlowSession session = initiateFlow(alice);
        session.send(number);

        int receivedPlusOneInt = session.receive(Integer.class).unwrap(it->it);

        return receivedPlusOneInt;
    }


}
